package com.example.administrator.managesystem.activity.my_profile;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.managesystem.R;
import com.example.administrator.managesystem.base.BaseActivity;
import com.example.administrator.managesystem.presenter.profile.ProfileChangePresenter;
import com.example.administrator.managesystem.presenter.profile.ProfilePresenter;
import com.example.administrator.managesystem.ui.ProfileView;
import com.example.administrator.managesystem.utils.GlobalConfig;
import com.example.administrator.managesystem.utils.LogUtil;
import com.example.administrator.managesystem.utils.PopUtils;
import com.example.administrator.managesystem.utils.ShareUtil;
import com.example.administrator.managesystem.view.CircleImageView;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.squareup.picasso.Picasso;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by Administrator on 2019/1/7.
 */

public class ProfileChangedActivity extends BaseActivity implements ProfileView {
    private TextView pop,camera,gallery,cancel,account_id,save_data,tag;
    private EditText name,age,charater;
    private CircleImageView circleImageView;
    private RadioButton male,female;
    private RadioGroup radioGroup;
    private WindowManager.LayoutParams params;
    private TagFlowLayout mFlowLayout;
    private TagAdapter<String> adapter;
    private RelativeLayout addr_rl;
    private TextView addr_tv;
    private EditText addr_et;
    private List<String> labels_list=new ArrayList<>();
    private List<String> datas = new ArrayList<>();
    private String province_selected, city_seleted,area_seleted;

    private String sex="f";
    //申明对象
    CityPickerView mPicker=new CityPickerView();

    private List<LocalMedia> selectList = new ArrayList<>();

    @Override
    public void initView() {
     showfloatButton(true,true);
        //预先加载仿iOS滚轮实现的全部数据
        mPicker.init(this);
      params = getWindow().getAttributes();
      pop=findViewById(R.id.edit_icon);
      addr_tv=findViewById(R.id.addr_tv);
      addr_et=findViewById(R.id.addr_et);
      circleImageView=findViewById(R.id.head_img);
      account_id=findViewById(R.id.user_id);
      save_data=findViewById(R.id.save_data);
      name=findViewById(R.id.name);
      age=findViewById(R.id.age);
      charater=findViewById(R.id.charater);
      male=findViewById(R.id.male);
      female=findViewById(R.id.female);
      radioGroup=findViewById(R.id.sex_rg);
      addr_rl=findViewById(R.id.addr_rl);
      mFlowLayout=findViewById(R.id.flowlayout);

        datas.add("果蔬类");
        datas.add("家禽类");
        datas.add("农牧类");
        datas.add("其他");

        adapter= new TagAdapter<String>(datas) {
            @Override
            public View getView(FlowLayout parent, int position, String o) {
                tag = (TextView) LayoutInflater.from(ProfileChangedActivity.this).inflate(R.layout.item_tag, parent,false);
                tag.setText(o);
                return tag;
            }
        };
        mFlowLayout.setAdapter(adapter);
    }

    @Override
    public void doBusiness() {
        name.setText(ShareUtil.getUserName(this));
        if(ShareUtil.getUserImg(this)==null){
            return;
        }else if(ShareUtil.getUserImg(this).isEmpty()){
            Picasso.with(this).load(R.mipmap.user_icon).into(circleImageView);
        } else if(ShareUtil.getUserIndex(this)){
            Picasso.with(this).load(new File(ShareUtil.getUserImg(this))).into(circleImageView);
        }else{
            Picasso.with(this).load(GlobalConfig.ONLINE_HTTP+""+ShareUtil.getUserImg(this)).into(circleImageView);
        }

        new ProfilePresenter(ProfileChangedActivity.this).profileInfoRequest(ShareUtil.getUserId(ProfileChangedActivity.this),ShareUtil.getUserToken(ProfileChangedActivity.this),ProfileChangedActivity.this);

        addr_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
        selectAddress();
            }
        });
        pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              showPop();
            }
        });
        save_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                labels_list.clear();
                Set<Integer> selectedList = mFlowLayout.getSelectedList();
                for (Integer integer : selectedList) {
                    labels_list.add(datas.get(integer));
                }
                Log.e("msg","list:"+ labels_list);
                Log.e("msg","province:"+ province_selected);
      new ProfileChangePresenter(ProfileChangedActivity.this).profileChangeRequest(ShareUtil.getUserId(ProfileChangedActivity.this),
              ShareUtil.getUserToken(ProfileChangedActivity.this),name.getText().toString(),sex,province_selected,city_seleted,area_seleted,age.getText().toString(),
              addr_et.getText().toString(),charater.getText().toString(),labels_list,ProfileChangedActivity.this);
            }
        });
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(RadioGroup group, int checkedId) {
          if(checkedId==R.id.female){
               sex="f";
          }else{
               sex="m";
          }
      }
  });

        adapter.setSelectedList(0);//默认选中第一个



    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_profile_change;
    }

    public void showPop(){
        params = getWindow().getAttributes();
        PopUtils utils = new PopUtils(ProfileChangedActivity.this, R.layout.camerca_pop, params.MATCH_PARENT,params.WRAP_CONTENT,pop, Gravity.BOTTOM, 0, 0, new PopUtils.ClickListener() {
            @Override
            public void setUplistener(final PopUtils.PopBuilder builder) {
                builder.setText(R.id.camera, "拍照");
                builder.getView(R.id.camera).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //              // 进入相册 以下是例子：不需要的api可以不写
                      PictureSelector.create(ProfileChangedActivity.this)
                      .openCamera(PictureMimeType.ofAll())
                      .imageFormat(PictureMimeType.PNG)
                      .previewImage(true)// 是否可预览图片
                      .selectionMode(PictureConfig.SINGLE)
                      .isCamera(true)
                      .compress(true)
                      .glideOverride(160, 160)
                      .minimumCompressSize(100)// 小于 100kb 的图片不压缩
                      .cropCompressQuality(90)// 裁剪压缩质量 默认100
                      .selectionMedia(selectList)
                      .forResult(PictureConfig.CHOOSE_REQUEST);
                        builder.dismiss();
                    }
                });
                builder.setText(R.id.gallery, "从相册里选择");
                builder.getView(R.id.gallery).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //              // 进入相册 以下是例子：不需要的api可以不写
                        PictureSelector.create(ProfileChangedActivity.this)
                                .openGallery(PictureMimeType.ofAll())
                                .imageFormat(PictureMimeType.PNG)
                                .previewImage(true)// 是否可预览图片
                                .selectionMode(PictureConfig.SINGLE)
                                .isCamera(true)
                                .compress(true)
                                .glideOverride(160, 160)
                                .minimumCompressSize(100)// 小于 100kb 的图片不压缩
                                .cropCompressQuality(90)// 裁剪压缩质量 默认100
                                .selectionMedia(selectList)
                                .forResult(PictureConfig.CHOOSE_REQUEST);

                        builder.dismiss();
                    }
                });

                builder.setText(R.id.cancel, "取消");
                builder.getView(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        builder.dismiss();
                    }
                });
            }
        }) {};

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList=PictureSelector.obtainMultipleResult(data);
                    Log.e("msg","selectList.get(0).getPath():"+selectList.get(0).getPath());
                    new ProfileChangePresenter(ProfileChangedActivity.this).headChangeRequest(ShareUtil.getUserId(ProfileChangedActivity.this),
                            ShareUtil.getUserToken(ProfileChangedActivity.this),selectList.get(0).getPath(),ProfileChangedActivity.this);
                    break;
            }
        }
    }

    private void selectAddress() {
        //添加默认的配置，不需要自己定义，当然也可以自定义相关熟悉，详细属性请看demo
        CityConfig cityConfig = new CityConfig.Builder()
                . title("选择您的地址")//标题
                .titleTextSize(16)//标题文字大小
                .titleTextColor("#333333")//标题文字颜色
                .titleBackgroundColor("#FFFFFF")//标题栏背景色
                .confirTextColor("#333333")//确认按钮文字颜色
                .confirmText("确定")//确认按钮文字
                .confirmTextSize(14)//确认按钮文字大小
                .cancelTextColor("#333333")//取消按钮文字颜色
                .cancelText("取消")//取消按钮文字
                .cancelTextSize(14)//取消按钮文字大小
                .setCityWheelType(CityConfig.WheelType.PRO_CITY_DIS)//显示类，只显示省份一级，显示省市两级还是显示省市区三级
                .showBackground(true)//是否显示半透明背景
                .visibleItemsCount(5)//显示item的数量
                .province(province_selected)//默认显示的省份
                .city(city_seleted)//默认显示省份下面的城市
                .district(area_seleted)//默认显示省市下面的区县数据
                .provinceCyclic(true)//省份滚轮是否可以循环滚动
                .cityCyclic(true)//城市滚轮是否可以循环滚动
                .districtCyclic(true)//区县滚轮是否循环滚动
                .drawShadows(true)//滚轮不显示模糊效果
                .setLineColor("#fce600")//中间横线的颜色
                .setShowGAT(true)//是否显示港澳台数据，默认不显示
                .build();
                mPicker.setConfig(cityConfig);


//监听选择点击事件及返回结果
        mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
               addr_tv.setText(province+"/"+city+"/"+district+"");
                province_selected=String.valueOf(province);
                city_seleted=String.valueOf(city);
                area_seleted= String.valueOf(district);
                //省份province
                //城市city
                //地区district
            }

            @Override
            public void onCancel() {
              //mPicker.hide();
            }
        });

        //显示
        mPicker.showCityPicker( );

    }


    @Override
    public void showMessage(File file,String url) {
        Picasso.with(ProfileChangedActivity.this).load(file).into(circleImageView);
        ShareUtil.saveUserHead(this,url);
        ShareUtil.saveUserIndex(this,true);
    }

    @Override
    public void navigateToHome(String name) {
        ShareUtil.saveUserName(this,name);
        finish();



    }

    @Override
    public void updateUI(String head_img, String address, int age, String area, String city, String id_card, String name, String province, String remarks, String sex, List<String> list) {

        this.addr_et.setText(address);
        this.name.setText(name);
        this.age.setText(""+age);
        province_selected=province;
        city_seleted=city;
        area_seleted=area;
        this.addr_tv.setText(province+"/"+city+"/"+area+"");
        this.charater.setText(remarks);
        this.account_id.setText(id_card);
        if(sex.equalsIgnoreCase("f")){
            female.setChecked(true);
            male.setChecked(false);
        }else{
            female.setChecked(false);
            male.setChecked(true);
        }
        Set<Integer> set = new HashSet<>();
        for(int i=0;i<datas.size();i++){
            for(int j=0;j<list.size();j++){
                if(datas.get(i).equalsIgnoreCase(list.get(j))){
                    set.add(i);
                    adapter.setSelectedList(set);
                }
            }
        }

    }


}
